<?php

// +----------------------------------------------------------------------
// | 版权所有 2017-2027 云南环拓科技有限公司，并保留所有权利。
// +----------------------------------------------------------------------
// | Copyright (c) 2017-2027 http://www.yn123.com All rights reserved.
// +----------------------------------------------------------------------
// | Notice: This code is not open source, it is strictly prohibited
// |         to distribute the copy, otherwise it will pursue its
// |         legal responsibility.
// | 注意：  这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用,
// |        不允许对程序代码以任何形式任何目的的再发布。
// +----------------------------------------------------------------------
// | Author: feraner <feraner@163.com> 
// | Date: 2019/10/25
// +----------------------------------------------------------------------

namespace app\common\tools;

use GuzzleHttp\Client;

/**
 * 工具帮助类
 * Class Help
 * @package app\common\tools
 * @author feraner<feraner@163.com>
 * @date 2019/10/25
 */
class Help
{

    /**
     * 判断是否是微信内置浏览器
     * @return bool
     */
    public function isWechat()
    {
        if(strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false){
            return 1;
        }
        return 0;
    }


    /**
     * 隐藏电话号码
     * @param $value
     *
     * @return mixed
     */
    public function ignoreMobile($value)
    {
        if ($value) {
            return substr_replace($value, '****', 3, 4);
        }
        return $value;
    }

    /**
     * 隐藏身份证信息
     * @param $value
     *
     * @return mixed
     */
    public function ignoreIdCard($value)
    {
        if ($value) {
            return substr_replace($value, '*********', 6, 9);
        }
        return $value;
    }


    /**
     * 一维数据数组生成数据树
     * @param array $list 数据列表
     * @param string $id 父ID Key
     * @param string $pid ID Key
     * @param string $son 定义子数据Key
     * @return array
     */
    public function arr2tree($list, $id = 'id', $pid = 'pid', $son = 'sub')
    {
        list($tree, $map) = [[], []];
        foreach ($list as $item) {
            $map[$item[$id]] = $item;
        }
        foreach ($list as $item) {
            if (isset($item[$pid]) && isset($map[$item[$pid]])) {
                $map[$item[$pid]][$son][] = &$map[$item[$id]];
            } else {
                $tree[] = &$map[$item[$id]];
            }
        }
        unset($map);
        return $tree;
    }

    /**
     * 地址解析成 经纬度
     * @param        $address
     * @param string $city
     */
    public function addressToLatLng($address, $city = '')
    {
        $result = [
            'lng'   => '',
            'lat'   => ''
        ];
        $client = new Client([
            'timeout'  => 5.0,
        ]);
        $url = 'https://apis.map.qq.com/ws/geocoder/v1/';
        $queryArr = [
            'address'       => $address,
            'key'           => config('lbs_qq_api_key'),
            'region'        => $city
        ];

        $sign = md5(
            '/ws/geocoder/v1/?address=' . $address . '&key=' .$queryArr['key'] .
            '&region=' . $city . config('lbs_qq_api_key_sign'));
        $url = $url . '?' . http_build_query($queryArr) . '&sig=' . $sign;
        $response = $client->get($url);
        if ($response->getStatusCode() == 200 && $response->getBody()->getSize()) {
            $content = $response->getBody()->getContents();
            $result = json_decode($content, true);
        }

        if (\app\common\facade\Arr::get($result, 'status') == 0) {
            $result = [
                'lng'       => \app\common\facade\Arr::get($result['result']['location'], 'lng'),
                'lat'       => \app\common\facade\Arr::get($result['result']['location'], 'lat')
            ];
        }
        return $result;
    }


    /**
     * 计算两个经纬度之间的距离
     * @param        $fromLocation
     * @param        $toLocation
     * @param string $type
     *
     * @return array|bool|mixed
     */
    public function computerDistance($fromLocation, $toLocation, $type = 'driving')
    {
        $result = false;
        $client = new Client([]);
        $url = 'https://apis.map.qq.com/ws/distance/v1';
        $queryArr = [
            'from'          => $fromLocation,
            'key'           => config('lbs_qq_api_key'),
            'mode'          => $type,
            'to'            => $toLocation,
        ];
        $sign = md5(
            '/ws/distance/v1?from=' . $queryArr['from']. '&key=' . $queryArr['key'] . '&mode=' . $type .
            '&to=' . $queryArr['to'] . config('lbs_qq_api_key_sign'));

        $url = $url . '?from=' . $queryArr['from']. '&key=' . $queryArr['key'] . '&mode=' . $type .
            '&to=' . $queryArr['to'] . '&sig=' . $sign;
        $response = $client->get($url);
        if ($response->getStatusCode() == 200 && $response->getBody()->getSize()) {
            $content = $response->getBody()->getContents();
            $result = json_decode($content, true);
            if (\app\common\facade\Arr::get($result, 'status') == 0) {
                $result = \app\common\facade\Arr::get($result['result']['elements'], 0);
                $result = [
                    'distance'      => \app\common\facade\Arr::get($result, 'distance'),
                    'time'          => \app\common\facade\Arr::get($result, 'duration')
                ];
            }
        }
        return $result;
    }


    /**
     * 经纬度转化成地址
     * @param $latitude
     * @param $longitude
     *
     * @return bool|mixed
     */
    public function latLongToLocation($latitude, $longitude)
    {
        $result = [];
        $client = new Client([]);
        $url = 'https://apis.map.qq.com/ws/geocoder/v1';
        $queryArr = [
            'location'          => $latitude . ',' . $longitude,
            'key'               => config('lbs_qq_api_key'),
            'get_poi'           => 0
        ];
        $sign = md5(
            '/ws/geocoder/v1?get_poi=' . $queryArr['get_poi']. '&key=' . $queryArr['key'] . '&location=' . $queryArr['location'] .
             config('lbs_qq_api_key_sign'));

        $url = $url . '?get_poi=' . $queryArr['get_poi']. '&key=' . $queryArr['key'] . '&location=' . $queryArr['location'] .
           '&sig=' . $sign;
        $response = $client->get($url);
        if ($response->getStatusCode() == 200 && $response->getBody()->getSize()) {
            $content = $response->getBody()->getContents();
            $result = json_decode($content, true);
            if (\app\common\facade\Arr::get($result, 'status') == 0) {
                $addressComponent = \app\common\facade\Arr::get($result['result'], 'address_component', []);
                if ($addressComponent) {
                    $result = [
                        'nationName'        => \app\common\facade\Arr::get($addressComponent, 'nation'),
                        'provinceName'      => \app\common\facade\Arr::get($addressComponent, 'province'),
                        'cityName'          => \app\common\facade\Arr::get($addressComponent, 'city'),
                        'countyName'        => \app\common\facade\Arr::get($addressComponent, 'district'),
                        'address'           => \app\common\facade\Arr::get($result['result'], 'address'),
                    ];
                }
            }
        }
        return $result;
    }



    /**
     * 处理地区后缀
     * @param $value
     *
     * @return mixed
     */
    public function ignoreAreaSuffix($value)
    {
        return str_replace(['镇', '县', '州', '乡', '村', '庄', '市', '省', '自治区', '行政区', '盟', '地区'], '', $value);
    }


    /**
     * 保存base64 图片
     * @param $imgContent
     * @param $savePath
     *
     * @return bool|string
     */
    public function saveBase64Img($imgContent, $savePath)
    {
        //匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $imgContent, $result)){
            $imgType = $result[2];
            $savePath = env('root_path'). 'public' . $savePath;
            if(!file_exists($savePath)){
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($savePath, 0777, true);
            }
            $fileName = uniqid() . '.'. $imgType;

            $fileSavePath = $savePath . $fileName;

            if (file_put_contents($fileSavePath, base64_decode(str_replace($result[1], '', $imgContent)))){
                return $fileName;
            }else{
                return false;
            }
        }else{
            return false;
        }

    }

}
